package com.w4cms.controller.admin;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.w4cms.interceptor.AdminInterceptor;
import com.w4cms.model.SysMenu;
import com.w4cms.model.SysRole;
import com.w4cms.utils.RightsUtils;
import com.w4cms.utils.Tools;
@ControllerBind(controllerKey="/admin/role",viewPath="admin/role")
@Before(AdminInterceptor.class)
public class RoleController extends Controller {
	public void list(){
		this.search();
	}
	public void add(){
		setAttr("menuNodes", JSONArray.toJSONString(SysMenu.dao.getMenuList(null)));
		render("roleinfo.html");
	}
	public void edit(){
		setAttr("menus", SysMenu.dao.getMenuList(null));
		Object id = getPara();
		SysRole role= SysRole.dao.findById(id);
		if(role==null){
			renderText("角色不存在.");
			return;
		}
		setAttr("role", role);
		String rights = role.getStr("rights");
		List<Map<String,Object>> list = SysMenu.dao.getMenuList(null);
		for(Map<String,Object> menu : list){
			Integer mid =(Integer)menu.get("id");
			if(RightsUtils.testRights(rights, mid)){
				menu.put("checked", true);
			}
		}
		
		setAttr("menuNodes", JSONArray.toJSONString(list));
		render("roleinfo.html");
	}
	public void save(){
		String id = getPara("id");
		String[] rights = getPara("rights","").split(",");
		BigInteger allRights = RightsUtils.sumRights(rights);
		boolean isOk = false;
		if(Tools.isEmpty(id)){
			isOk = new SysRole().set("name", getPara("name")).set("remark", getPara("remark")).set("rights", allRights).saveRole();
		}else{
			isOk = new SysRole().set("id", id).set("name", getPara("name")).set("remark", getPara("remark")).set("rights", allRights).updateRole();
		}
		if(isOk){
			renderJson("success",true);
		}else{
			renderJson("msg","操作失败.");
		}
	}
	
	
	public void search(){
		String search = getPara("search");
		Integer pageNumber = getParaToInt("p",1);
		if(pageNumber<1){
			pageNumber=1;
		}
		Integer pageSize = getParaToInt("r",15);
		if(pageSize<1 || pageSize>100){
			pageSize = 15;
		}
		Page<SysRole> list = SysRole.dao.searchRoles(pageNumber, pageSize, search);
		setAttr("roles", list);
		setAttr("pageStr", Tools.getPageStr(list));
		keepPara();
		render("rolelist.html");
	}
}
